import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { createServer as createViteServer } from 'vite';


const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function createServer({ isPord = false }) {
  console.log(isPord);
  const app = express();
  let vite;
  if (!isPord) {
    vite = await createViteServer({
      server: { middlewareMode: true },
      appType: 'custom',
      // base:"/dist/client/"
    });
    // 这是适用于开发模式下的中间件
    // 主要作用是代理静态资源，静态资源托管
    app.use(vite.middlewares);
    // 为了解决开发模式下的闪屏问题，需要将dist/client下的静态资源托管
    app.use(
      (await import('serve-static')).default(path.resolve(__dirname, './dist/client'), {
        index: false,
      })
    );
  } else {
    app.use((await import('compression')).default());
    app.use(
      (await import('serve-static')).default(path.resolve(__dirname, './dist/client'), {
        index: false,
      })
    );
  }
  app.use('*', async (req, res) => {
    const url = req.originalUrl;
    let template;
    let render;
    if (!isPord) {
      template = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8');
      template = await vite.transformIndexHtml(url, template);
      const {renderDev} = (await vite.ssrLoadModule('./src/entry.server.jsx'))
      render =  renderDev 
      const appHtml =await render(url);
      const html = template.replace("<!--ssr-outlet-->", appHtml);
      res.status(200).set({ "Content-Type": "text/html" }).end(html);
    } else {
      template = fs.readFileSync(path.resolve(__dirname, 'dist/client/index.html'), 'utf-8');
      render = (await import('./dist/server/entry.server.js')).render;
      render(url, res);
    }

  });

  app.listen(5173);
}

createServer({
  isPord: true,
});
